package cn.tedu.s1.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@Controller
public class ToolsController {
    /**
     * 生成验证码的
     * @param request
     * @param response
     */
    @RequestMapping("/myweb/random.jpg")
    public void createRandomImage(HttpServletResponse response){
        Random random = new Random();
        BufferedImage image = new BufferedImage(70,30,BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        Color bgcolor = new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256));
        g.setColor(bgcolor);
        g.fillRect(0,0,70,30);
        String line = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        g.setFont(new Font(null, Font.BOLD, 20));
        for(int i=0;i<4;i++) {
            String c = line.charAt(random.nextInt(line.length())) + "";
            g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
            g.drawString(c, i*15+5, 18+(random.nextInt(11)-5));
        }
        for(int i=0;i<5;i++) {
            g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
            g.drawLine(random.nextInt(71), random.nextInt(31),
                    random.nextInt(71), random.nextInt(31));
        }
        try {
            response.setContentType("image/jpeg");
            ImageIO.write(image,"jpg",response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
